/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test_system.user_logic;

import test_system.parser.ParseRefactor;
import test_system.parser.ParserCSV;
import test_system.questions.QuestionWrapper;
import test_system.questions.TestWrapper;

/**
 *
 * @author root
 */
public class SessionRestore {

    String[][] fileContent;

    public RestoreInfo restore(String fileName) {
        fileContent = getInformation(fileName);
        Session session = restoreSession();
        String[] userAnswers = restoreUserAnswer();
        TestWrapper test = restoreTest();
        return new RestoreInfo(test, userAnswers, session);
    }

    private Session restoreSession() {
        String[] userPart = fileContent[0];
        return Session.createSession(userPart[0], userPart[1]);
    }

    private String[] restoreUserAnswer() {
        return fileContent[1];
    }

    private TestWrapper restoreTest() {
        String[] testData = fileContent[2];
        StringBuffer questionBuff;
        StringBuffer testBuff = new StringBuffer();
        for (String question : testData) {
            questionBuff = stringToBuffWithSeparator(question, "|", ",");
            testBuff.append(questionBuff);
            testBuff.append("\n");
        }
        ParseRefactor parseRefactor = new ParseRefactor();
        return parseRefactor.createTest(testBuff);
    }

    private StringBuffer stringToBuffWithSeparator(String target, String oldSeparator, String newSeparator) {
        StringBuffer result = new StringBuffer();
        String[] array = target.split(oldSeparator);
        for (String string : array) {
            result.append(string);
            result.append(newSeparator);
        }
        return result;
    }

    private String[][] getInformation(String fileName) {
        ParserCSV parser = new ParserCSV();
        StringBuffer fileContent = parser.parseFile(fileName);
        String[] partFileContent = fileContent.toString().split(";");
        String[][] result = new String[partFileContent.length][];
        for (int i = 0; i < partFileContent.length; i++) {
            result[i] = partFileContent[i].split(",");
        }
        return result;
    }
}
